//
//  STDSRenderThread.m
//  STDRenderSDK
//
//  Created by 陈学明 on 2023/3/16.
//

#import "STDSRenderThread.h"

@interface STDSRenderThread ()
@property (nonatomic, strong) NSThread *mThread;
@property (nonatomic, strong) NSPort *mMachPort;
@property (nonatomic, strong) void(^mBlock)(void);
@property (nonatomic, weak) NSRunLoop *mRunloop;
@property (nonatomic, assign) BOOL isLoopRunning;
@end

@implementation STDSRenderThread

- (instancetype)init {
    self = [super init];
    if (self) {
        __weak STDSRenderThread *weakSelf = self;
        _mThread = [[NSThread alloc] initWithTarget:weakSelf selector:@selector(renderThreadFunc) object:nil];
        [_mThread start];
    }
    return self;
}

- (void)addOperationWithBlock:(void(^)(void))block {
    [self performSelector:@selector(onRenderLoopWithBlock:) onThread:self.mThread withObject:block waitUntilDone:NO];
}

- (void)renderThreadFunc {
    // 开启 runloop
    self.mRunloop = [NSRunLoop currentRunLoop];
    self.mMachPort = [NSMachPort port];
    [self.mRunloop addPort:self.mMachPort forMode:NSDefaultRunLoopMode];
    self.isLoopRunning = YES;
    while (self.isLoopRunning && [self.mRunloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
//    NSLog(@"dealloc--runloop已退出");
}

- (void)onRenderLoopWithBlock:(void(^)(void))block {
    if (block) {
        block();
    }
}

- (void)close {
    [self performSelector:@selector(closeThread) onThread:self.mThread withObject:nil waitUntilDone:NO];
}

- (void)closeThread {
    self.isLoopRunning = NO;
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)dealloc {
    NSLog(@"dealloc--STDSRenderThread");
}

@end
